package com.zhou.service.impl.event;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.zhou.configure.PushConfigure;
import com.zhou.dto.IdentityInfo;
import com.zhou.repository.DistrictIdRepository;
import com.zhou.repository.IdentityInfoDataRepository;
import com.zhou.service.WxEventStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author lcz
 * @desc 选址策略
 * @mail lcz_0130@163.com
 * @date 2023/12/28
 */

@Service("LOCATION")
@Slf4j
public class LocationStrategy implements WxEventStrategy {
    @Resource
    private PushConfigure pushConfigure;
    @Resource
    private DistrictIdRepository districtIdRepository;
    @Resource
    private IdentityInfoDataRepository identityInfoDataRepository;

    @Override
    public void execute(Map<String, String> requestMap, HttpServletResponse response) throws Exception {
        log.info("事件类型：位置");

        log.info("事件类型：LOCATION");
        IdentityInfo identityInfo = new IdentityInfo();
        identityInfo.setAppId(pushConfigure.getAppId());
        identityInfo.setAppSecret(pushConfigure.getSecret());
        String openId = requestMap.get("FromUserName");
        identityInfo.setOpenId(openId);
        identityInfo.setPublicId(requestMap.get("ToUserName"));
        // 纬度
        String latitude = requestMap.get("Latitude");
        identityInfo.setLatitude(latitude);
        // 经度
        String longitude = requestMap.get("Longitude");
        identityInfo.setLongitude(longitude);
        // 根据经纬度获取地址的url
        String searchAddressUrl = "https://api.map.baidu.com/reverse_geocoding/v3/?ak=" + pushConfigure.getBaidu_ak() +
                "&output=json&coordtype=wgs84ll&location=" + latitude + "," + longitude;
        String addressStr = HttpUtil.get(searchAddressUrl);
        // 处理json串的jsonObject对象
        String result = JSONObject.parseObject(addressStr).get("result").toString();
        JSONObject resultObject = JSONObject.parseObject(result);
        // 详细地址
        String address = resultObject.get("formatted_address").toString();
        JSONObject addressComponent = JSONObject.parseObject(resultObject.get("addressComponent").toString());
        // 国家
        String country = addressComponent.get("country").toString();
        // 省份
        String province = addressComponent.get("province").toString();
        // 市
        String city = addressComponent.get("city").toString();
        // 区
        String district = addressComponent.get("district").toString();
        identityInfo.setAddress(address);
        identityInfo.setCountry(country);
        identityInfo.setProvince(province);
        identityInfo.setCity(city);
        identityInfo.setDistrict(district);

        districtIdRepository.findAll().forEach(districtId -> {
            if (districtId.getCity().equals(city) && districtId.getDistrict().equals(district.substring(0, district.length() - 1))) {
                identityInfo.setDistrictId(districtId.getDistrict_geocode());
            }
        });

        log.info("更新用户位置信息：{}", identityInfo);
        if (StringUtils.isNoneBlank(latitude, longitude)) {
            //根据openid查询用户信息
            IdentityInfo identityInfo1 = identityInfoDataRepository.findByOpenId(openId);
            if (identityInfo1 != null) {
                identityInfo.setId(identityInfo1.getId());
            }
            // 更新数据库里的位置信息(走到位置策略这里一定是在表中有记录，直接更新全量的数据)
            identityInfoDataRepository.save(identityInfo);
        }
    }
}
